﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text;
using System.Web;
using Liber;
using Liber.WEB;
using System.Net;

namespace FlashQ.Main.Pay
{
    /// <summary>
    /// 支付宝支付相关接口的封装
    /// </summary>
    public class AliPay: IPayProvider
    {
        static string APPID;
        static string MID;
        static string PvtKEY;
        static string PvtKeyPEM;
        static string PKey;
        static string AliPubKEY;
        static string AliPubKeyPEM;
        static string BaseURL;

        public AliPay(){
            var cfg = XMLSetting.DefaultSetting.First("Pay").First("AliPay");
            APPID = cfg.First("AppID").Value;
            MID = cfg.First("MerchantID").Value;
            PvtKEY = cfg.First("PrivateKey").Value;
            PvtKeyPEM = cfg.First("PrivateKeyPCKS1").Value;
            PKey = cfg.First("PublicKey").Value;
            AliPubKEY = cfg.First("AliPubKey").Value;
            AliPubKeyPEM = cfg.First("AliPubKeyPEMPCKS1").Value;
            BaseURL = cfg.First("GateWay").Value;
        }

        public FnResult<DyObject> NewAppPay(string trade_no,decimal total_amount,string subject) {
            DateTime tm = DateTime.Now;
            DyObject bizContent = new DyObject().Set("total_amount", total_amount)
                                                .Set("subject", subject)
                                                .Set("out_trade_no", trade_no);

            string bizCntStr =bizContent.FastJson();

            StringBuilder toSign = new StringBuilder();
            toSign.AppendFormat("app_id={0}&biz_content={1}&charset=UTF-8&method=alipay.trade.app.pay&sign_type=RSA2&timestamp={2}&version=1.0", APPID, bizCntStr, tm.ToString("yyyy-MM-dd HH:mm:ss"));

            StringBuilder args = new StringBuilder();
            args.AppendFormat(@"app_id={0}&biz_content={1}&charset=UTF-8&method={2}&sign_type=RSA2&timestamp={3}&version={4}",
                APPID,
                WebUtility.UrlEncode(bizCntStr),
                WebUtility.UrlEncode("alipay.trade.app.pay"),
                WebUtility.UrlEncode(tm.ToString("yyyy-MM-dd HH:mm:ss").Replace("+","%20")),
                WebUtility.UrlEncode("1.0"));

            string sign = RSAHelper.SignSHA256(PvtKEY, toSign.ToString());
            sign = WebUtility.UrlEncode(sign);

            return FnResult<DyObject>.Sucess(new DyObject().Set("order_info", args.ToString() + "&sign=" + sign));
        }
    }
}
